Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
    }
    return fmt; 
}
var store = {
	save(key,value){localStorage.setItem(key,JSON.stringify(value))},
	fetch(key){return JSON.parse(localStorage.getItem(key)) || [];}
}

var runTimeHandle=null;
var userId=store.fetch("userId");
var sort=store.fetch("sort")//当前选择的任务类型
var vm = new Vue({
	el: ".main",
	data: {
		list:[],
		task:"",
		editItem:"",
		loginTip:"",
		departList:[],
		user:{name:"",pwd:"",departNo:""},
		beforeTitle:"",
		visibility:"all",
		inputId:"",
		run:{time:0},
		notExist:true,
		runItem:{},//运行中item
		sort:sort,//当前选择的任务类型 默认选择0 0-计划任务 1-实际任务  
		sorts:["创建计划任务，回车添加","创建新任务，回车添加","创建季度OKR，回车添加"],
		userId:userId
	},	
	watch:{
		list:{
			handler:function(){
				axios.post("/task/synTask",{tasks:this.list},function(res){
					console.info(res)
				})
			},
			deep:true
		},
		userId:{
			handler:function(){
				store.save("userId",this.userId)
			},
		},
		sort:{
			handler:function(){
				store.save("sort",this.sort)
			},
		}
	},
	computed:{
		unCheckedLength(){
			return  this.filter(1,false).length
		},
		finishedPlIST(){	
			return this.filter(0,true);
		},
		unfinishedPlIST(){//未完成的计划
			return this.filter(0,false);
		},
		finishedAlIST(){//完成的临时任务				
			return this.filter(1,true);
		},
		unfinishedAlIST(){//未完成的临时任务				
			return this.filter(1,false);
		},
		okrList(){
			return this.filter(2,false);
		}
		
	},
	methods: {
		cgesort(sort){//改变任务类型
			this.sort=sort;
		},
		filter(sort,checked){
			return this.list.filter(function(item) {
				return item.del==0&&item.sort==sort&&item.checked==checked;
			});
		},
		addRunTime(){
			this.run.time=this.run.time+1;
		},
		addTodo(ev){
			var now=new Date();
			if(this.task !== ""){
				var item = {
					taskId:now.format("yyyyMMddhhmmss")+Math.floor(Math.random()*10),
					task:this.task,
					checked:false,
					sort:this.sort,
					startTime:now.format("hh:mm"),
					endTime:(now.getHours()+2)+":"+now.getMinutes(),
					status:0,//创建任务 0 暂停执行
					lastSaveRuntime:0,//上一次保存的运行时间
					timeList:[],
					createDate:now.format("yyyy-MM-dd"),
					userId:this.userId,
					del:0
				}
				this.list.push(item)
			this.task = "";
			}
		},
		deleteTodo(item){
			item.del=1;
		},
		editTodo(item){	
			this.beforeTitle = item.task;
			this.editItem = item;
		},
		edited(item){
			this.editItem = ""
		},
		cancel(item){
			item.task =  this.beforeTitle;
			this.editItem = "";
			this.beforeTitle = ""
		},
		opTask(item){
			clearInterval(runTimeHandle)
			this.allPause();
			item.status++;
			if(item.status>1){
				item.status=0;
			}	
			if(item.status==1){
				this.startTask(item)
			}
		},
		startTask(item){
			item.startTime=Date.now();
			this.runItem=item;
			clearInterval(runTimeHandle);
			this.run.time=item.lastSaveRuntime;
			runTimeHandle=setInterval(this.addRunTime,1000)
		},
		continueTask(){
			clearInterval(runTimeHandle);
			runTimeHandle=setInterval(this.addRunTime,1000)
		},
		showTime(second,item){
			if(item){
				if(this.run.time<=0){
					this.run.time=item.lastSaveRuntime+parseInt((Date.now()-item.startTime)/1000);
					second=this.run.time;
				}
				this.continueTask();
			}
			if(second<60){
				return "0:"+(second<10?"0"+second:second); 
			}
			var min=parseInt(second/60)　;
			var sec=second % 60;
			if(min<60){
				return min+":"+(sec<10?"0"+sec:sec);
			}
			var hour=parseInt(min/60)　;
			var min=min%60;
			return hour+":"+(min<10?"0"+min:min)+":"+(sec<10?"0"+sec:sec);
		},
		allPause(){
			for(var i=0;i<this.unfinishedAlIST.length;i++){
				var item=this.unfinishedAlIST[i]
				if(item.status==1){
					item.endTime=Date.now();
					item.lastSaveRuntime=this.run.time;
					item.timeList.push([item.startTime,item.endTime]);
					item.startTime=0;
				}
				item.status=0;
			}
		},
		finishTask(item){
			item.status=0;
			item.endTime=Date.now();
			item.lastSaveRuntime=this.run.time;
			item.timeList.push([item.startTime,item.endTime]);
			item.startTime=0;
			if(this.unfinishedAlIST.length>0){
				this.unfinishedAlIST[0].status=1;
				this.startTask(this.unfinishedAlIST[0]);
			}
			console.info(this.list)
		},
		login(){
			this.loginTip="";
			if(!this.user.name||!this.user.pwd){
				this.loginTip="请输入用户名或密码";
				return ;
			}
			if(!this.user.departNo&&this.notExist){
				this.loginTip="请选择部门";
				return ;
			}
			axios.post("/user/login",this.user).then((res)=>{
				var data=res.data;
				if(data.status==0){
					this.userId=res.data.data.userId
					location.reload();
				}else{
					this.loginTip=data.msg;
				}
			 }).catch((error)=>{
				 this.loginTip=error;
			 });
		},
		checkUser(){
			axios.post("/user/checkUser",this.user).then((res)=>{
				var data=res.data;
				this.notExist=data
			 }).catch((error)=>{
				 this.loginTip=error;
			 });
		}
	},
	directives:{
		"focus":{									
			update(el,binding){
				if(binding.value){
					el.focus()
				}

			}
		}
	}
});

function watchHashChange(){
	var hash = window.location.hash.slice(1);
	vm.visibility = hash;
};

watchHashChange();

window.addEventListener("hashchange",watchHashChange)
function loadTasks(){
	if(userId.length>0){
		axios({
		    method: 'get',
		    url:"/task/list/"+userId,
		}).then((res)=>{
			vm.list=res.data.data;
		})	
	}
}
loadTasks();
axios({
    method: 'get',
    url:"/depart/list",
}).then((res)=>{
	vm.departList=res.data.data;
})